﻿using System.Threading.Tasks;
using Linker.TaskCenter.Helpers;
using Quartz;
using Volo.Abp.BackgroundWorkers.Quartz;

namespace Linker.TaskCenter.Tasks
{
    [DisallowConcurrentExecution]
    public class TaskRetryWorker : QuartzBackgroundWorkerBase
    {
        private readonly CSRedisHelper _redisHelper;
        private readonly ITaskManager _taskManager;

        public TaskRetryWorker(
            ITaskManager taskManager,
            CSRedisHelper redisHelper)
        {
            _taskManager = taskManager;
            _redisHelper = redisHelper;

            JobDetail = JobBuilder.Create<TaskRetryWorker>()
                .WithIdentity(nameof(TaskRetryWorker))
                .Build();
            Trigger = TriggerBuilder.Create()
                .WithIdentity(nameof(TaskRetryWorker))
                .StartNow()
                .WithSimpleSchedule(s => s.WithIntervalInMinutes(1).RepeatForever())
                .Build();
        }


        public override Task Execute(IJobExecutionContext context)
        {
            while (true)
            {
                var data = _redisHelper.BRPop<RequestMessageData>(AppConsts.RetryTaskQueueKey);
                if (data == null)
                {
                    return Task.CompletedTask;
                }
                _taskManager.ExecuteTaskAsync(data);
            }
        }
    }
}